package com.demo.logistics.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import com.demo.logistics.stockControl.data.DatabaseDescriptor;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseAdapter {
	// private static final String DATABASE_NAME = "myDatabase.db";
	// private static final String DATABASE_TABLE = "mainTable";
	private static final int DATABASE_VERSION = 1;
	// The index (key) column name for use in where clauses.
	// public static final String KEY_ID="_id";
	// The name and column index of each column in your database.
	// public static final String KEY_NAME="name";
	// public static final int NAME_COLUMN = 1;
	// TODO: Create public field for each column in your table.
	// SQL Statement to create a new database.
	// Variable to hold the database instance
	private SQLiteDatabase db;
	// Context of the application using the database.
	private final Context context;
	// Database open/upgrade helper
	private myDbHelper dbHelper;

	public DatabaseAdapter(Context _context) {
		context = _context;
		dbHelper = new myDbHelper(context, DatabaseDescriptor.getDbName(),
				null, DATABASE_VERSION);
	}

	public DatabaseAdapter open() {
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
	}

	public int insertEntry(Object[] items, String tableName) {
		int index = 0;
		ContentValues newValues = new ContentValues();
		if (items != null && items.length > 0) {
			// String firstItem = (String) items[0];
			// boolean isDup = checkDuplicatedFirstItem(firstItem);
			System.out.println("***Inserting into database...***");
			for (int i = 0; i < items.length; i++) {
				if (items[i] != null) {
					System.out.println("item" + i + ": " + items[i].toString());
					newValues.put(DatabaseDescriptor.getColumnName(tableName,
							i, false), items[i].toString());
				} else {
					System.out.println("item" + i + " is null");
				}
			}
			index = (int) db.insert(tableName, null, newValues);
		}
		return index;
	}

	// public boolean removeEntry(long _rowIndex) {
	// return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
	// }
	public ArrayList<Object[]> getAllEntries(String tableName) {
		String[] colNamesFinal = DatabaseDescriptor
				.getAllColumnNames(tableName);
		ArrayList<Object[]> rtnArrList = new ArrayList<Object[]>();
		System.out.println("***BEGIN getAllEntries***");
		Cursor cur = db.query(tableName, colNamesFinal, null, null, null, null,
				null);
		if (cur != null) {
			System.out.println("moved to first cursor");
			cur.moveToFirst();
			int x=0;
			while (cur.isAfterLast() == false) {
				Object[] tempObj = new Object[colNamesFinal.length];
				System.out.println("BEGIN ROW"+x);
				for (int i = 0; i < colNamesFinal.length; i++) {
					if (DatabaseDescriptor.getColumnType(tableName, i, true)
							.equals("real")) {
						tempObj[i] = cur.getDouble(i);
					} else if (DatabaseDescriptor.getColumnType(tableName, i,
							true).equals("text")) {
						tempObj[i] = cur.getString(i);
					} else if (DatabaseDescriptor.getColumnType(tableName, i,
							true).equals("integer")) {
						tempObj[i] = cur.getInt(i);
					}
					else{
						tempObj[i] = cur.getString(i);
					}
					if(tempObj[i]==null){
						tempObj[i] = " ";
					}
					System.out.print("col"+i+": "+tempObj[i].toString()+"  ");
				}
				System.out.println("END ROW"+x);
				rtnArrList.add(tempObj);
				cur.moveToNext();
				x++;
			}
		}
		cur.close();
		System.out.println("***END getAllEntries***");
		return rtnArrList;
	}

	// public MyObject getEntry(long _rowIndex) {
	// TODO: Return a cursor to a row from the database and
	// use the values to populate an instance of MyObject
	// return objectInstance;
	// }
	// public boolean updateEntry(long _rowIndex, MyObject _myObject) {
	// TODO: Create a new ContentValues based on the new object
	// and use it to update a row in the database.
	// return true;
	// }
	private static class myDbHelper extends SQLiteOpenHelper {
		public myDbHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
		}

		// Called when no database exists in disk and the helper class needs
		// to create a new one.
		@Override
		public void onCreate(SQLiteDatabase _db) {
			String[] allStmt = DatabaseDescriptor.getAllCreateStmt();
			for (int i = 0; i < allStmt.length; i++) {
				_db.execSQL(allStmt[i]);
			}
		}

		// Called when there is a database version mismatch meaning that the
		// version
		// of the database on disk needs to be upgraded to the current version.
		@Override
		public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
				int _newVersion) {
			// Log the version upgrade.
			Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion
					+ " to " + _newVersion
					+ ", which will destroy all old data");
			// Upgrade the existing database to conform to the new version.
			// Multiple
			// previous versions can be handled by comparing _oldVersion and
			// _newVersion
			// values.
			// The simplest case is to drop the old table and create a new one.
			String[] allStmt = DatabaseDescriptor.getAllDropStmt();
			for (int i = 0; i < allStmt.length; i++) {
				_db.execSQL(allStmt[i]);
			}
			// Create a new one.
			onCreate(_db);
		}
	}
}
